package com.chanjiedata.changbs.module.count;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.chanjiedata.changbs.R;
import com.chanjiedata.changbs.base.BaseFragment;
import com.chanjiedata.changbs.net.Apis;
import com.chanjiedata.changbs.net.NetworkManager;
import com.chanjiedata.changbs.net.interfaces.OnRequestCallBack;
import com.chanjiedata.changbs.proto.Statistics;
import com.chanjiedata.changbs.utlis.DateUtil;
import com.chanjiedata.changbs.utlis.DialogUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.google.protobuf.InvalidProtocolBufferException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/2/2 0002.
 */

public class CountFourthFragment extends BaseFragment {


    Unbinder unbinder;
    @BindView(R.id.btn_day)
    RadioButton btnDay;
    @BindView(R.id.btn_week)
    RadioButton btnWeek;
    @BindView(R.id.btn_month)
    RadioButton btnMonth;
    @BindView(R.id.rg_date_type)
    RadioGroup rgDateType;
    @BindView(R.id.chart)
    LineChart chart;
    @BindView(R.id.chart_two)
    LineChart chartTwo;
    @BindView(R.id.tv_select_time)
    TextView tvSelectTime;
    @BindView(R.id.tv_count_time)
    TextView tvCountTime;


    private String search_type = "1";  //  1 日  2 周  3 月
    private String search_time_end = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    private DatePickerDialog.OnDateSetListener onDateSetListener;
    private List<Entry> entries = new ArrayList<>();
    private List<Entry> entriesTwo = new ArrayList<>();


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_count_fourth;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initView() {
        tvSelectTime.setText(search_time_end);
        tvCountTime.setText(search_time_end);
        initListener();
        initLineChart();
        initLineChartTwo();
        LoadLinedData("1", entries, chart);
        LoadLinedData("2", entriesTwo, chartTwo);
    }

    private void initLineChart() {
        // 手势禁用
        chart.setTouchEnabled(false);
        Description description = new Description();
        description.setText("");
        chart.setDescription(description);


        //设置样式
        YAxis rightAxis = chart.getAxisRight();

        //设置图表右边的y轴禁用
        rightAxis.setEnabled(false);

        YAxis LeftAxis = chart.getAxisLeft();
        // 设置坐标轴的标签数量，当count>25时，count=25；当count<2时，count=2
        LeftAxis.setLabelCount(6);
        LeftAxis.setTextColor(Color.parseColor("#6F889C"));
        LeftAxis.setAxisMinimum(0); //设置Y轴是否从0开始

        //设置x轴
        XAxis xAxis = chart.getXAxis();
        xAxis.setTextColor(Color.parseColor("#6F889C"));
        xAxis.setTextSize(11f);
        xAxis.setAxisMinimum(0f);
        xAxis.setDrawAxisLine(false);//是否绘制轴线
        xAxis.setDrawGridLines(false);//设置x轴上每个点对应的线
        xAxis.setGridColor(Color.parseColor("#26070707"));
        xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置
        xAxis.setGranularity(1);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getAxisLabel(float value, AxisBase axis) {
                if (value < entries.size()) {
                    return entries.get((int) value).getData().toString();
                } else {
                    return "";
                }
            }
        });

        //透明化图例
        Legend legend = chart.getLegend();
        legend.setEnabled(false);


    }

    private void initLineChartTwo() {
        // 手势禁用
        chartTwo.setTouchEnabled(false);
        Description description = new Description();
        description.setText("");
        chartTwo.setDescription(description);


        //设置样式
        YAxis rightAxis = chartTwo.getAxisRight();

        //设置图表右边的y轴禁用
        rightAxis.setEnabled(false);

        YAxis LeftAxis = chartTwo.getAxisLeft();
        // 设置坐标轴的标签数量，当count>25时，count=25；当count<2时，count=2
        LeftAxis.setLabelCount(6);
        LeftAxis.setTextColor(Color.parseColor("#6F889C"));
        LeftAxis.setAxisMinimum(0); //设置Y轴是否从0开始

        //设置x轴
        XAxis xAxis = chartTwo.getXAxis();
        xAxis.setTextColor(Color.parseColor("#6F889C"));
        xAxis.setTextSize(11f);
        xAxis.setAxisMinimum(0f);
        xAxis.setDrawAxisLine(false);//是否绘制轴线
        xAxis.setDrawGridLines(false);//设置x轴上每个点对应的线
        xAxis.setGridColor(Color.parseColor("#26070707"));
        xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置
        xAxis.setGranularity(1);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getAxisLabel(float value, AxisBase axis) {
                if (value < entries.size()) {
                    return entries.get((int) value).getData().toString();
                } else {
                    return "";
                }
            }
        });

        //透明化图例
        Legend legend = chartTwo.getLegend();
        legend.setEnabled(false);


    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        rgDateType.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.btn_day:
                    search_type = "1";
                    tvCountTime.setText(search_time_end);
                    break;
                case R.id.btn_week:
                    search_type = "2";
                    tvCountTime.setText(DateUtil.getSpecifiedDayBefore(search_time_end, 6));
                    break;
                case R.id.btn_month:
                    search_type = "3";
                    tvCountTime.setText(DateUtil.getSpecifiedDayBefore(search_time_end, 29));
                    break;
            }
            LoadLinedData("1", entries, chart);
            LoadLinedData("2", entriesTwo, chartTwo);
        });

        onDateSetListener = (datePicker, year, month, day) -> {
            search_time_end = year + "-" + (month + 1) + "-" + day;
            tvSelectTime.setText(search_time_end);
            switch (search_type) {
                case "1":
                    tvCountTime.setText(search_time_end);
                    break;
                case "2":
                    tvCountTime.setText(DateUtil.getSpecifiedDayBefore(search_time_end, 6));
                    break;
                case "3":
                    tvCountTime.setText(DateUtil.getSpecifiedDayBefore(search_time_end, 29));
                    break;
            }
            LoadLinedData("1", entries, chart);
            LoadLinedData("2", entriesTwo, chartTwo);
        };
        tvSelectTime.setOnClickListener(v -> {
            DialogUtils.showDatePickerDialog(getActivity(), onDateSetListener, Calendar.getInstance());
        });

    }

    /**
     * 加载折线图数据
     */
    private void LoadLinedData(String type, List<Entry> tempentries, LineChart temp_chart) {
        Statistics.get_increase.Builder builder = Statistics.get_increase.newBuilder();
        builder.setSearchType(search_type).setType(type).setSearchTimeEnd(search_time_end);
        NetworkManager.INSTANCE.post(Apis.get_increase, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                List<Statistics.basis> lists = Statistics.get_increase.parseFrom(bytes).getArrayList();
                Log.e("wang", "onOk: " + lists.toString());
                setLineData(lists, tempentries, temp_chart);
            }

            @Override
            public void onError(int code, String errorMessage) {
            }
        });
    }

    private void setLineData(List<Statistics.basis> lists, List<Entry> entries, LineChart chart) {
        //1.设置x轴和y轴的点
        entries.clear();
        for (int i = 0; i < lists.size(); i++)
            entries.add(new Entry(i, Float.valueOf(lists.get(i).getNum()), lists.get(i).getName()));
        LineDataSet dataSet = new LineDataSet(entries, "1"); // add entries to dataset
        dataSet.setColor(Color.parseColor("#8A9EC1FF"));//线条颜色
        dataSet.setCircleColor(Color.parseColor("#28AFE9"));//圆点颜色
        dataSet.setDrawFilled(true);  // 设置是否填充
        dataSet.setDrawCircleHole(false);  // 设置是否实心
        dataSet.setLineWidth(1.0f);//线条宽度
        dataSet.setValueTextColor(Color.parseColor("#28AFE9"));
        dataSet.setValueTextSize(9);
        //3.chart设置数据
        LineData lineData = new LineData(dataSet);
        chart.setData(lineData);
        chart.notifyDataSetChanged();
        chart.animateY(500); // refresh
    }

    @Override
    protected void init() {

    }

    public void reLoadData() {
        LoadLinedData("1", entries, chart);
        LoadLinedData("2", entriesTwo, chartTwo);
    }
}
